<?php

namespace App\Task\Video;

use App\Cache\InviteVideoCache;
use App\Cache\RedisKey;
use App\Helpers\RedisUtil;
use App\Model\PayOrder;
use App\Model\User;
use App\Model\UserProfile;
use App\Model\VoiceCall;
use App\Service\ServiceTrait\InviteVideoCheckTrait;
use Hyperf\Crontab\Annotation\Crontab;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 检测邀约空闲的邀约视频
 * @Crontab(name="InviteVideoTask", rule="*\/30 * * * * *", callback="execute", memo="检测邀约空闲的邀约视频",singleton=false)
 */
class InviteVideoTask
{
    use InviteVideoCheckTrait;

    /**
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function execute()
    {
        $onlineUser = UserProfile::getOnlineUserAll();

        if (empty($onlineUser)){
            log_info('InviteVideoTask:info:NoOnlineUserList');
            return;
        }

        $redis = RedisUtil::getRedis();

        $key = RedisKey::joinInviteVideoToday();
        $maleKey = RedisKey::inviteVideoMaleLock();
        $femaleKey = RedisKey::inviteVideoFemaleLock();

        InviteVideoCache::buildKey([$key,$maleKey,$femaleKey]);

        $joinList = array_diff($redis->sMembers($key),[0]);
        if (empty($joinList)){
            log_info('InviteVideoTask:info:NoVideoInviteList');
            return;
        }

        $maleLockList = array_diff($redis->sMembers($maleKey),[0]);
        $femaleLockList = array_diff($redis->sMembers($femaleKey),[0]);

        $lockList = array_merge($maleLockList,$femaleLockList);

        $payUserList = array_values(array_unique(PayOrder::getIsPayAll()));
        $runList = array_diff($joinList,$lockList,$payUserList);

        //取交集
        $dataList = array_values(array_unique(array_intersect($runList,$onlineUser)));

        if (empty($dataList)){
            log_info('InviteVideoTask:info:NoLeisureVideoInviteList');
            return;
        }

        foreach ($dataList as $one)
        {
            $this->runInvite($one);
        }

        log_info('InviteVideoTask:info:RunList:date:'.date('Ymd-His'));
    }
}